/// Interface-based SOA Code and Documentation Generator
// - this unit is a part of the Open Source Synopse mORMot framework 2,
// licensed under a MPL/GPL/LGPL three license - see LICENSE.md
unit mormot.soa.codegen;

{
  *****************************************************************************

   SOA API Code and Documentation Generation
    - ORM and SOA Logic Extraction from RTTI
    - Documentation Extraction from Source Code Comments
    - Doc/CodeGen wrapper Functions on Server Side
    - FPC Dedicated Generators
    - Compute Asynchronous Code from Synchronous Interface
    - Generate Code and Doc from Command-Line

  *****************************************************************************
}

interface

{$I ..\mormot.defines.inc}

uses
  sysutils,
  classes,
  variants,
  {$ifdef ISDELPHI}
  typinfo, // for proper Delphi inlining
  {$endif ISDELPHI}
  mormot.core.base,
  mormot.core.os,
  mormot.core.buffers,
  mormot.core.unicode,
  mormot.core.text,
  mormot.core.variants,
  mormot.core.data,
  mormot.core.datetime,
  mormot.core.rtti,
  mormot.core.json,
  mormot.core.interfaces,
  mormot.core.mustache,
  mormot.orm.base,
  mormot.orm.core,
  mormot.orm.rest,
  mormot.soa.core,
  mormot.soa.server,
  mormot.rest.core,
  mormot.rest.server,
  mormot.rest.memserver;


{ ************ ORM and SOA Logic Extraction from RTTI }

/// compute the Model information, ready to be exported as JSON
// - will publish the ORM and SOA properties
// - to be used e.g. for client code generation via Mustache templates
// - optional aSourcePath parameter may be used to retrieve additional description
// from the comments of the source code of the unit - this text content may
// also be injected by WRAPPER_RESOURCENAME
// - you may specify a description file (as generated by FillDescriptionFromSource)
function ContextFromModel(aServer: TRestServer;
  const aSourcePath: TFileName = '';
  const aDescriptions: TFileName = ''): variant;

/// compute the SOA information, ready to be exported as JSON
// - will publish the ORM and SOA properties
// - to be used e.g. for client code generation via Mustache templates
function ContextFromUsedInterfaces(const aSourcePath: TFileName = '';
  const aDescriptions: TFileName = ''): variant;

/// compute the information of an interface method, ready to be exported as JSON
// - to be used e.g. for the implementation of the MVC controller via interfaces
// - no description text will be included - use ContextFromModel() if needed
function ContextFromMethod(const method: TInterfaceMethod): variant;

/// compute the information of an interface, ready to be exported as JSON
// - to be used e.g. for the implementation of the MVC controller via interfaces
// - no description text will be included - use ContextFromModel() if needed
function ContextFromMethods(int: TInterfaceFactory): variant;


{ ************ Doc/CodeGen wrapper Functions on Server Side }

/// generate a code/doc wrapper for a given Model and Mustache template content
// - will use all ORM and SOA properties of the supplied server
// - aFileName will be transmitted as {{filename}}, e.g. 'mORMotClient'
// - you should also specify a "fake" HTTP port e.g. 888
// - the template content could be retrieved from a file via StringFromFile()
// - you may optionally retrieve a copy of the data context as TDocVariant
// - this function may be used to generate the client at build time, directly
// from a just built server, in an automated manner
// - you may specify custom helpers (e.g. via TSynMustache.HelpersGetStandardList)
// and retrieve the generated data context after generation (if aContext is
// a TDocVariant object, its fields would be added to the rendering context),
// or a custom description file (as generated by FillDescriptionFromSource)
function WrapperFromModel(aServer: TRestServer;
  const aMustacheTemplate, aFileName: RawUtf8; aPort: integer;
  aHelpers: TSynMustacheHelpers = nil;
  aContext: PVariant = nil;
  const aDescriptions: TFileName = ''): RawUtf8;

/// generate a code/doc wrapper for a given set of types and Mustache template content
// - will use aTables[] to define the ORM information, and supplied aSharedServices[]
// aSharedServicesContract[] for SOA definition of a shared API (expected to
// be called from TRestClientUri.ServiceDefineSharedApi)
// - aFileName will be transmitted as {{filename}}, e.g. 'mORMotClient'
// - you should also specify a "fake" HTTP port e.g. 888
// - the template content could be retrieved from a file via StringFromFile()
// - you may optionally retrieve a copy of the data context as TDocVariant
// - this function may be used to generate the client at build time, directly
// from a just built server, in an automated manner
// - you may specify custom helpers (e.g. via TSynMustache.HelpersGetStandardList)
// and retrieve the generated data context after generation (if aContext is
// a TDocVariant object, its fields would be added to the rendering context),
// or a custom description file (as generated by FillDescriptionFromSource)
function WrapperForPublicAPI(const aTables: array of TOrmClass;
  const aRoot, aMustacheTemplate, aFileName: RawUtf8;
  const aSharedServices: array of TGuid;
  const aSharedServicesContract: array of RawUtf8;
  aResultAsJsonObjectWithoutResult: boolean; aPort: integer;
  aHelpers: TSynMustacheHelpers = nil; aContext: PVariant = nil;
  const aDescriptions: TFileName = ''): RawUtf8;

/// instantiate a TRest server instance, including supplied ORM and SOA definitions
// - will use aTables[] to define the ORM information, and supplied aSharedServices[]
// aSharedServicesContract[] for SOA definition of a shared API, implemented as
// abstract classes using TInterfaceStub
// - as used e.g. by WrapperForPublicAPI() to generate some code/doc wrappers
function WrapperFakeServer(const aTables: array of TOrmClass;
  const aRoot: RawUtf8;
  const aSharedServices: array of TGuid;
  const aSharedServicesContract: array of RawUtf8;
  aResultAsJsonObjectWithoutResult: boolean): TRestServerFullMemory;

/// you can call this procedure within a method-based service allow
// code-generation of an ORM and SOA client from a web browser
// - you have to specify one or several client *.mustache file paths
// - the first path containing any *.mustache file will be used as templates
// - for instance:
// ! procedure TCustomServer.Wrapper(Ctxt: TRestServerUriContext);
// ! begin // search in the current path
// !   WrapperMethod(Ctxt,['.']);
// ! end;
// - optional SourcePath parameter may be used to retrieve additional description
// from the comments of the source code of the unit
// - you may specify a description file (as generated by FillDescriptionFromSource)
procedure WrapperMethod(Ctxt: TRestServerUriContext;
  const Path: array of TFileName;
  const SourcePath: TFileName = '';
  const Descriptions: TFileName = '');

/// you can call this procedure to add a 'Wrapper' method-based service
//  to a given server, to allow code-generation of an ORM and SOA client
// - you have to specify one or several client *.mustache file paths
// - the first path containing any *.mustache file will be used as templates
// - if no path is specified (i.e. as []), it will search in the .exe folder
// - the root/wrapper URI will be accessible without authentication (i.e.
// from any plain browser)
// - for instance:
// ! aServer := TRestServerFullMemory.Create(aModel,'test.json',false,true);
// ! AddToServerWrapperMethod(aServer,['..']);
// - optional SourcePath parameter may be used to retrieve additional description
// from the comments of the source code of the unit
procedure AddToServerWrapperMethod(Server: TRestServer;
  const Path: array of TFileName;
  const SourcePath: TFileName = '');


{ ************ Documentation Extraction from Source Code Comments }

/// rough parsing of the supplied .pas unit, adding the /// commentaries
// into a TDocVariant content
procedure FillDescriptionFromSource(var Descriptions: TDocVariantData;
  const SourceFileName: TFileName);

/// rough parsing of the supplied .pas unit, adding the /// commentaries
// into a compressed binary resource
// - could be then compiled into a WRAPPER_RESOURCENAME resource, e.g. via the
// following .rc source file, assuming ResourceDestFileName='wrapper.desc':
// $ WrappersDescription 10 "wrapper.desc"
// - you may specify a .json file name, for debugging/validation purposes
// - calls internally FillDescriptionFromSource
// - returns the TDocVariant JSON object corresponding to all decriptions
function ResourceDescriptionFromSource(const ResourceDestFileName: TFileName;
  const SourceFileNames: array of TFileName;
  const JsonDestFileName: TFileName = ''): variant;

const
  /// internal Resource name used for bounded description
  // - as generated by FillDescriptionFromSource/ResourceDescriptionFromSource
  // - would be used e.g. by TWrapperContext.Create to inject the available
  // text description from any matching resource
  WRAPPER_RESOURCENAME = 'WrappersDescription';

var
  /// how FillDescriptionFromSource() handles trailing '-' in parsed comments
  // - default is [*], as expected by buggy AsciiDoc format
  DESCRIPTION_ITEM_PREFIX: RawUtf8 = ' [*]';


{ ************ FPC Dedicated Generators }

/// you can call this procedure to generate the mORMotServer.pas unit needed
// to compile a given server source code using FPC
// - will locate FPCServer-mORMotServer.pas.mustache in the given Path[] array
// - will write the unit using specified file name or to mORMotServer.pas in the
// current directory if DestFileName is '', or to a sub-folder of the matching
// Path[] if DestFileName starts with '\' (to allow relative folder use)
// - the missing RTTI for records and interfaces would be defined, together
// with some patch comments for published record support (if any) for the ORM
procedure ComputeFPCServerUnit(Server: TRestServer; const
  Path: array of TFileName;
  DestFileName: TFileName = '');

/// you can call this procedure to generate the mORMotInterfaces.pas unit needed
// to register all needed interface RTTI for FPC
// - to circumvent http://bugs.freepascal.org/view.php?id=26774 unresolved issue
// - will locate FPC-mORMotInterfaces.pas.mustache in the given Path[] array
// - will write the unit using specified file name or to mORMotInterfaces.pas in
// the current directory if DestFileName is '', or to a sub-folder of the
// matching Path[] if DestFileName starts with '\' (to allow relative folder use)
// - all used interfaces will be exported, including SOA and mocking/stubing
// types: so you may have to run this function AFTER all process is done
procedure ComputeFPCInterfacesUnit(const Path: array of TFileName;
  DestFileName: TFileName = '');


{ ************ Compute Asynchronous Code from Synchronous Interface }


/// this function would generate a pascal unit defining asynchronous
// (non-blocking) types from a DDD's blocking dual-phase Select/Command service
// - you should specify the services to be converted, as an array - note that
// due to how RTTI is stored by the compiler, all "pure input" parameters should
// be defined explicitly as "const", otherwise the generated class won't match
// - optionally, the TCQRSServiceClass implementing the first Select() phase of
// the blocking service may be specified in queries array; a set of unit names
// in which those TCQRSServiceClass are defined may be specified
// - a Mustache template content should be provided - e.g. asynch.pas.mustache
// as published in SQLite3\DDD\dom folder of the source code repository
// - FileName would contain the resulting unit filename (without the .pas)
// - ProjectName would be written in the main unit comment
// - CallType should be the type used at Domain level to identify each
// asynchronous call - this type should be an integer, or a function may be
// supplied as CallFunction (matching VariantToInteger signature)
// - the first phase of the service should have set Key: KeyType, which would be
// used to create a single shared asynchronous service instance for all keys
// - ExceptionType may be customize, mainly to use a Domain-specific class
// - blocking execution may reach some timeout waiting for the asynchronous
// acknowledgement: a default delay (in ms) is to be supplied, and some custom
// delays may be specified as trios, e.g. ['IMyInterface', 'Method', 10000, ...]
function GenerateAsynchServices(const services: array of TGuid;
  const queries: array of TClass;
  const units: array of const;
  const additionalcontext: array of const;
  Template, FileName, ProjectName, CallType, CallFunction,
  Key, KeyType, ExceptionType: RawUtf8;
  DefaultDelay: integer; const CustomDelays: array of const): RawUtf8;


{ ************ Generate Code and Doc from Command-Line }

type
  /// the options retrieved during a ExecuteFromCommandLine() call
  TServiceClientCommandLineOptions = set of (
    cloPrompt,
    cloNoColor,
    cloPipe,
    cloHeaders,
    cloVerbose,
    cloNoExpand,
    cloNoBody);

  /// event handler to let ExecuteFromCommandLine call a remote server
  // - before call, aParams.InBody will be set with the expected JSON content
  TOnCommandLineCall = procedure(aOptions: TServiceClientCommandLineOptions;
    const aService: TInterfaceFactory; aMethod: PInterfaceMethod;
    var aParams: TRestUriParams) of object;

const
  /// help information displayed by ExecuteFromCommandLine() with no command
  // - note that Windows and POSIX don't handle the double quotes similarly,
  // so putting JSON on the command line could be tricky and needs ' escaping
  EXECUTEFROMCOMMANDLINEHELP =
   ' % help  -> show all services (interfaces)'#13#10 +
   ' % [service] [help]  -> show all methods of a given service'#13#10 +
   ' % [service] [method] help -> show parameters of a given method'#13#10 +
   ' % [options] [service] [method] [parameters] -> call a given method ' +
   {$ifdef OSWINDOWS}
   'with [parameters] being name=value or name=""value with spaces"" or ' +
   'name:={""some"":""json""}' +
   ' and [options] as /nocolor /pipe /headers /verbose /noexpand /nobody';
   {$else}
   'with [parameters] being name=value or name=''"value with spaces"'' or ' +
   'name:=''{"some":"json"}''' +
   ' and [options] as --nocolor --pipe --headers --verbose --noexpand --nobody';
   {$endif OSWINDOWS}

/// command-line SOA remote access to mORMot interface-based services
// - supports the EXECUTEFROMCOMMANDLINEHELP commands
// - you shall have registered the aServices interface(s) by a previous call to
// the overloaded Get(TypeInfo(IMyInterface)) method or RegisterInterfaces()
// - you may specify an optional description file, as previously generated
// by mormot.soa.codegen.pas' FillDescriptionFromSource function - a local
// 'WrappersDescription' resource will also be checked
// - to actually call the remote server, aOnCall should be supplied
procedure ExecuteFromCommandLine(
  const aServices: array of TGuid;
  const aOnCall: TOnCommandLineCall;
  const aDescriptions: TFileName = '');



implementation

{ ************ ORM and SOA Logic Extraction from RTTI }

type
  /// a cross-platform published property kind
  // - does not match mormot.orm.core.pas TOrmFieldType: here we recognize only
  // types which may expect a special behavior in SynCrossPlatformREST.pas unit
  // - should match TOrmFieldKind order in SynCrossPlatformREST.pas
  TCrossPlatformOrmFieldKind = (
    cpkDefault,
    cpkDateTime,
    cpkTimeLog,
    cpkBlob,
    cpkModTime,
    cpkCreateTime,
    cpkRecord,
    cpkVariant);

const
  /// those text values should match TOrmFieldKind in SynCrossPlatformREST.pas
  // - was previously named sft* in mORMot 1.18
  CROSSPLATFORMKIND_TEXT: array[TCrossPlatformOrmFieldKind] of RawUtf8 = (
    'oftUnspecified',
    'oftDateTime',
    'oftTimeLog',
    'oftBlob',
    'oftModTime',
    'oftCreateTime',
    'oftRecord',
    'oftVariant');

type
  /// types recognized and handled by this mormot.soa.codegen.pas unit
  TWrapperType = (
    wUnknown,
    wBoolean,
    wEnum,
    wSet,
    wByte,
    wWord,
    wInteger,
    wCardinal,
    wInt64,
    wQWord,
    wID,
    wReference,
    wTimeLog,
    wModTime,
    wCreateTime,
    wCurrency,
    wSingle,
    wDouble,
    wDateTime,
    wRawUtf8,
    wString,
    wRawJson,
    wBlob,
    wGuid,
    wCustomAnswer,
    wRecord,
    wArray,
    wVariant,
    wObject,
    wORM, // was wSQLRecord
    wInterface,
    wRecordVersion);

  /// supported languages typesets
  TWrapperLanguage = (
    lngDelphi,
    lngPascal,
    lngCS,
    lngJava,
    lngTypeScript,
    lngSwagger);

const
  CROSSPLATFORM_KIND: array[TOrmFieldType] of TCrossPlatformOrmFieldKind =(
    cpkDefault,    // oftUnknown
    cpkDefault,    // oftAnsiText
    cpkDefault,    // oftUtf8Text
    cpkDefault,    // oftEnumerate
    cpkDefault,    // oftSet
    cpkDefault,    // oftInteger
    cpkDefault,    // oftID
    cpkDefault,    // oftRecord
    cpkDefault,    // oftBoolean
    cpkDefault,    // oftFloat
    cpkDateTime,   // oftDateTime
    cpkTimeLog,    // oftTimeLog
    cpkDefault,    // oftCurrency
    cpkDefault,    // oftObject
    cpkVariant,    // oftVariant
    cpkVariant,    // oftNullable
    cpkBlob,       // oftBlob
    cpkDefault,    // oftBlobDynArray
    cpkDefault,    // oftBlobCustom
    cpkRecord,     // oftUtf8Custom
    cpkDefault,    // oftMany
    cpkModTime,    // oftModTime
    cpkCreateTime, // oftCreateTime
    cpkDefault,    // oftTID
    cpkDefault,    // oftRecordVersion
    cpkDefault,    // oftSessionUserID
    cpkDateTime,   // oftDateTimeMS
    cpkDefault,    // oftUnixTime
    cpkDefault);   // oftUnixMSTime

  SIZETODELPHI: array[0..8] of string[7] = (
    'integer', 'byte', 'word', 'integer',
    'integer', 'int64', 'int64', 'int64', 'int64');

  TYPES_SIZE: array[0..8] of TWrapperType = (
    wInteger, wByte, wWord, wInteger,
    wInteger, wInt64, wInt64, wInt64, wInt64);

  // Swagger numerical types
  SWI32 = '{"type":"integer"}';
  SWI64 = '{"type":"integer","format":"int64"}';
  SWD32 = '{"type":"number","format":"float"}';
  SWD64 = '{"type":"number","format":"double"}';

  { TODO: refactor TID and Int64 for JavaScript? (integers truncated to 53-bit) }
  TYPES_LANG: array[TWrapperLanguage, TWrapperType] of RawUtf8 = (
    // lngDelphi
    ('', 'Boolean', '', '', 'Byte', 'Word', 'Integer', 'Cardinal', 'Int64',
    'UInt64', 'TID', 'TRecordReference', 'TTimeLog', 'TModTime', 'TCreateTime',
    'Currency', 'Single', 'Double', 'TDateTime', 'RawUtf8', 'String', 'RawJson',
    'RawBlob', 'TGuid', 'TServiceCustomAnswer', '', '', 'Variant', '', '', '',
    'TRecordVersion'),
   // lngPascal
    ('', 'Boolean', '', '', 'Byte', 'Word', 'Integer', 'Cardinal', 'Int64',
    'UInt64', 'TID', 'TRecordReference', 'TTimeLog', 'TModTime', 'TCreateTime',
    'Currency', 'Single', 'Double', 'TDateTime', 'String', 'String', 'Variant',
    'RawBlob', 'TGuid', 'THttpBody', '', '', 'Variant', '', 'TID', '', 'TRecordVersion'),
   // lngCS
    ('', 'bool', '', '', 'byte', 'word', 'integer', 'uint', 'long', 'ulong',
    'TID', 'TRecordReference', 'TTimeLog', 'TModTime', 'TCreateTime', 'decimal',
    'single', 'double', 'double', 'string', 'string', 'dynamic', 'byte[]',
    'Guid', 'byte[]', '', '', 'dynamic', '', 'TID', '', 'TRecordVersion'),
   // lngJava
    ('', 'boolean', '', '', 'byte', 'int', 'int', 'long', 'long', 'long', 'TID',
    'TRecordReference', 'TTimeLog', 'TModTime', 'TCreateTime', 'BigDecimal',
    'single', 'double', 'double', 'String', 'String', 'Object', 'byte[]',
    'String', 'byte[]', '', '', 'Object', '', 'TID', '', 'TRecordVersion'),
   // lngTypeScript
    ('', 'boolean', '', '', 'number', 'number', 'number', 'number', 'number',
    'number', 'mORMot.TID', 'mORMot.TRecordReference', 'mORMot.TTimeLog',
    'mORMot.TModTime', 'mORMot.TCreateTime', 'number', 'number', 'number',
    'mORMot.TDateTime', 'string', 'string', 'any', 'mORMot.RawBlob',
    'mORMot.TGuid', 'mORMot.THttpBody', '', '', 'any', '', '', '',
    'mORMot.TRecordVersion'),
   // lngSwagger
    ('', '{"type":"boolean"}', '', '', SWI32, SWI32, SWI32, SWI32, SWI64, SWI64,
    SWI64, SWI64, SWI64, SWI64, SWI64, SWD64, SWD32, SWD64,
    '{"type":"string","format":"date-time"}', // wDateTime
    '{"type":"string"}', '{"type":"string"}', '{"type":"object"}', //FIXME! //wRawJson
    '{"type":"string","format":"binary"}', '{"type":"string"}', //wBlob,wGuid
    '', '', '', '', //wCustomAnswer, wRecord, wArray, wVariant
    '', SWI64, '', '' //wObject, wORM, wInterface, wRecordVersion
    ));
  TYPES_ORM: array[TOrmFieldType] of TWrapperType = (
    wUnknown,        // oftUnknown
    wString,         // oftAnsiText
    wRawUtf8,        // oftUtf8Text
    wEnum,           // oftEnumerate
    wSet,            // oftSet
    wUnknown,        // oftInteger - wUnknown to force exact type
    wORM,            // oftID
    wReference,      // oftRecord
    wBoolean,        // oftBoolean
    wUnknown,        // oftFloat - wUnknown to force exact type
    wDateTime,       // oftDateTime
    wTimeLog,        // oftTimeLog
    wCurrency,       // oftCurrency
    wObject,         // oftObject
    wVariant,        // oftVariant
    wVariant,        // oftNullable
    wBlob,           // oftBlob
    wArray,          // oftBlobDynArray - with specific code below
    wRecord,         // oftBlobCustom
    wRecord,         // oftUtf8Custom
    wUnknown,        // oftMany
    wModTime,        // oftModTime
    wCreateTime,     // oftCreateTime
    wID,             // oftID
    wRecordVersion,  // oftRecordVersion
    wID,             // oftSessionUserID
    wDateTime,       // oftDateTimeMS
    wUnknown,        // oftUnixTime
    wUnknown);       // oftUnixMSTime

  TYPES_SIMPLE: array[TRttiParserType] of TWrapperType = (
    wUnknown,  //  ptNone
    wArray,    //  ptArray
    wBoolean,  //  ptBoolean
    wByte,     //  ptByte
    wCardinal, //  ptCardinal
    wCurrency, //  ptCurrency
    wDouble,   //  ptDouble
    wDouble,   //  ptExtended
    wInt64,    //  ptInt64
    wInteger,  //  ptInteger
    wQWord,    //  ptQWord
    wBlob,     //  ptRawByteString
    wRawJson,  //  ptRawJson
    wRawUtf8,  //  ptRawUtf8
    wRecord,   //  ptRecord
    wSingle,   //  ptSingle
    wString,   //  ptString
    wRawUtf8,  //  ptSynUnicode
    wDateTime, //  ptDateTime
    wDateTime, //  ptDateTimeMS
    wGuid,     //  ptGuid
    wBlob,     //  ptHash128
    wBlob,     //  ptHash256
    wBlob,     //  ptHash512
    wID,       //  ptOrm
    wTimeLog,  //  ptTimeLog
    wRawUtf8,  //  ptUnicodeString
    wInt64,    //  ptUnixTime
    wInt64,    //  ptUnixMSTime
    wVariant,  //  ptVariant
    wRawUtf8,  //  ptWideString
    wRawUtf8,  //  ptWinAnsi
    wWord,     //  ptWord
    wEnum,     //  ptEnumeration
    wSet,      //  ptSet
    wUnknown,  //  ptClass
    wArray,    //  ptDynArray - with specific code below
    wUnknown,  //  ptInterface
    wRawUtf8,  //  ptPUtf8Char
    wUnknown); //  ptCustom

  TYPES_SOA: array[TInterfaceMethodValueType] of TWrapperType = (
    wUnknown,  // imvNone
    wUnknown,  // imvSelf
    wBoolean,  // imvBoolean
    wEnum,     // imvEnum
    wSet,      // imvSet
    wUnknown,  // imvInteger
    wUnknown,  // imvCardinal
    wUnknown,  // imvInt64
    wDouble,   // imvDouble
    wDateTime, // imvDateTime
    wCurrency, // imvCurrency
    wRawUtf8,  // imvRawUtf8
    wString,   // imvString
    wRawUtf8,  // imvRawByteString
    wRawUtf8,  // imvWideString
    wRecord,   // imvRecord
    wVariant,  // imvVariant
    wObject,   // imvObject
    wRawJson,  // imvRawJson
    wArray,    // imvDynArray
    wUnknown); // imvInterface
    // integers are wUnknown to force best type recognition

type
  EWrapperContext = class(ESynException);

  /// this non-published class is used internally to extract info from RTTI
  TWrapperContext = class
  protected
    fServer: TRestServer;
    fORM, fRecords, fEnumerates, fSets, fArrays: TDocVariantData;
    fUnits, fDescriptions: TDocVariantData;
    fSOA: variant;
    fSourcePath: TFileNameDynArray;
    fHasAnyRecord: boolean;
    fNestedId: integer; // for unique nested type names if no RTTI
    function ContextFromRtti(typ: TWrapperType; rtti: TRttiCustom = nil;
      typName: RawUtf8 = ''; const parentName: RawUtf8 = ''): variant;
    function ContextNestedProperties(rtti: TRttiCustom;
      const parentName: RawUtf8): variant;
    function ContextOneProperty(const prop: TRttiCustomProp;
      const parentName: RawUtf8): variant;
    function ContextFromMethods(int: TInterfaceFactory): variant;
    function ContextFromMethod(const meth: TInterfaceMethod): variant;
    function ContextArgsFromMethod(const meth: TInterfaceMethod): variant;
    procedure AddUnit(const aUnitName: ShortString; addAsProperty: PVariant);
  public
    constructor Create(const aSourcePath, aDescriptions: TFileName);
    constructor CreateFromModel(aServer: TRestServer;
      const aSourcePath: TFileName; const aDescriptions: TFileName);
    constructor CreateFromUsedInterfaces(
      const aSourcePath, aDescriptions: TFileName);
    function Context: variant;
  end;


{ TWrapperContext }

constructor TWrapperContext.Create(const aSourcePath, aDescriptions: TFileName);
var
  desc: RawByteString;
  source: TFileName;
  src: PChar;
  n: PtrInt;
begin
  TDocVariant.NewFast([
    @fORM,
    @fRecords,
    @fEnumerates,
    @fSets,
    @fArrays,
    @fUnits,
    @fDescriptions]);
  if aDescriptions <> '' then
    desc := StringFromFile(aDescriptions);
  if {%H-}desc = '' then
    ResourceSynLZToRawByteString(WRAPPER_RESOURCENAME, desc);
  if desc <> '' then
    fDescriptions.InitJsonInPlace(pointer(desc), JSON_FAST);
  if aSourcePath <> '' then
  begin
    src := pointer(aSourcePath);
    n := 0;
    repeat
      source := GetNextItemString(src, ';');
      if (source <> '') and
         DirectoryExists(source) then
      begin
        SetLength(fSourcePath, n + 1);
        fSourcePath[n] := IncludeTrailingPathDelimiter(source);
        inc(n);
      end;
    until src = nil;
  end;
end;

function TWrapperContext.ContextNestedProperties(rtti: TRttiCustom;
  const parentName: RawUtf8): variant;
var
  i: PtrInt;
begin
  SetVariantNull(result);
  case rtti.Parser of
    ptRecord,
    ptClass:
      ; // use rtti.Props
    ptArray,
    ptDynArray:  // use array item (may be nil for static unmanaged)
      rtti := rtti.ArrayRtti;
  else
    exit; // no nested properties
  end;
  TDocVariant.NewFast(result);
  if rtti <> nil then
    for i := 0 to rtti.Props.Count - 1 do
      TDocVariantData(result).AddItem(
        ContextOneProperty(rtti.Props.List[i], parentName));
end;

function ClassToWrapperType(c: TClass): TWrapperType;
begin
  if c.InheritsFrom(TOrm) then
    result := wORM
  else
    result := wObject;
end;

function TWrapperContext.ContextFromRtti(typ: TWrapperType; rtti: TRttiCustom;
  typName: RawUtf8; const parentName: RawUtf8): variant;
var
  typAsName: PShortString;

  function VarName(lng: TWrapperLanguage): variant;
  begin
    if TYPES_LANG[lng, typ] <> '' then
      RawUtf8ToVariant(TYPES_LANG[lng, typ], result)
    else if typName = '' then
      SetVariantNull(result)
    else
      RawUtf8ToVariant(typName, result);
  end;

  function VarSwagger: variant;
  begin
    if TYPES_LANG[lngSwagger, typ] <> '' then
      result := _JsonFast(TYPES_LANG[lngSwagger, typ])
    else if typName = '' then
      SetVariantNull(result)
    else
      RawUtf8ToVariant(typName, result);
  end;

  procedure RegisterType(var list: TDocVariantData);
  var
    info: variant;
  begin
    if list.SearchItemByProp('name', typName, false) >= 0 then
      // already registered
      exit;
    if rtti = nil then
      EWrapperContext.RaiseUtf8('%.RegisterType(%): no RTTI', [typAsName^, typName]);
    case typ of
      wEnum,
      wSet:
        // include (untrimed) identifier: values[] may be trimmed at mustache level
        info := _JsonFastFmt('{name:?,values:%}',
          [rtti.Cache.EnumInfo^.GetEnumNameAllAsJsonArray(false)], [typName]);
      wRecord:
        if rtti.Props.Count <> 0 then
          info := _ObjFast([
            'name',      typName,
            'camelName', LowerCamelCase(typName),
            'snakeName', SnakeCase(typName),
            'fields',    ContextNestedProperties(rtti, parentName)]);
      wArray:
        begin
          if rtti.ObjArrayClass <> nil then
          begin
            info := ContextFromRtti(
              ClassToWrapperType(rtti.ObjArrayClass), rtti.ArrayRtti);
            _Safe(info)^.AddValue('isObjArray', true);
          end
          else
          begin
            if rtti.ArrayRtti = nil then
              if rtti.Cache.ItemSize > high(TYPES_SIZE) then
                // to avoid buffer overflow
                info := ContextFromRtti(wRawUtf8)
              else
                info := ContextFromRtti(TYPES_SIZE[rtti.Cache.ItemSize])
            else if rcfBinary in rtti.ArrayRtti.Flags then
              info := ContextFromRtti(wRawUtf8)
            else
              info := ContextFromRtti(wUnknown, rtti.ArrayRtti);
          end;
          // can be used to create static array (dynamic arrays have ItemCount=0)
          //  array{{#staticMaxIndex}}[0..{{staticMaxIndex}}]{{/staticMaxIndex}} of
          _ObjAddProps([
            'name',      typName,
            'camelName', LowerCamelCase(typName),
            'snakeName', SnakeCase(typName)], info);
          if rtti.Cache.ItemCount > 0 then
            _Safe(info)^.AddValue('staticMaxIndex', rtti.Cache.ItemCount-1);
        end;
    end;
    if not VarIsEmptyOrNull(info) then
      // null e.g. for a record without custom text definition
      list.AddItem(info);
  end;

begin
  // retrieve typ from RTTI if needed
  if typ = wUnknown then
  begin
    if rtti = nil then
      EWrapperContext.RaiseUtf8(
        '%.ContextFromRtti: No RTTI nor typ for [%]', [self, typName]);
    typ := TYPES_ORM[GetOrmFieldType(rtti.Info)];
    if typ = wUnknown then
    begin
      typ := TYPES_SIMPLE[rtti.Parser];
      if typ = wUnknown then
        case rtti.Kind of
          {$ifdef FPC}rkObject,{$else}{$ifdef UNICODE}rkMRecord,{$endif}{$endif}
          rkRecord:
            typ := wRecord;
          rkInterface:
            typ := wInterface;
        else
          EWrapperContext.RaiseUtf8(
            '%.ContextFromRtti: Not enough RTTI for [%]', [self, rtti.Name]);
        end;
    end;
  end;
  if (typ = wRecord) and
     PropNameEquals(typName, 'TGUID') then
    typ := wGuid
  else if (typ = wRecord) and
          PropNameEquals(typName, 'TServiceCustomAnswer') then
    typ := wCustomAnswer;
  // set typName/typAsName
  if typName = '' then
    if rtti <> nil then
      if rcfWithoutRtti in rtti.Flags then // undefined nested fields
        FormatUtf8('T%%', [parentName, InterlockedIncrement(fNestedId)], typName)
      else
        typName := rtti.Name
    else
      typName := TYPES_LANG[lngDelphi, typ];
  typAsName := GetEnumName(TypeInfo(TWrapperType), ord(typ));
  // generate basic context as TDocVariant fields
  result := _ObjFast([
    'typeWrapper', typAsName^,
    'typeSource',  typName,
    'typeDelphi',  VarName(lngDelphi),
    'typePascal',  VarName(lngPascal),
    'typeCS',      VarName(lngCS),
    'typeJava',    VarName(lngJava),
    'typeTS',      VarName(lngTypeScript),
    'typeSwagger', VarSwagger]);
  if self = nil then
    // no need to have full info if called e.g. from MVC
    exit;
  // add special marshalling information
  if rtti <> nil then
    case rtti.Kind of
      rkClass:
        AddUnit(rtti.Info^.RttiClass^.UnitName^, @result);
    end;
  case typ of
    wBoolean,
    wByte,
    wWord,
    wInteger,
    wCardinal,
    wInt64,
    wQWord,
    wID,
    wReference,
    wTimeLog,
    wModTime,
    wCreateTime,
    wSingle,
    wDouble,
    wRawUtf8,
    wString:
      ; // simple types have no special marshalling
    wDateTime:
      _ObjAddProps(['isDateTime',  true,
                    'toVariant',   'DateTimeToIso8601',
                    'fromVariant', 'Iso8601ToDateTime'], result);
    wRecordVersion:
      _ObjAddProp('isRecordVersion', true, result);
    wCurrency:
      _ObjAddProp('isCurrency', true, result);
    wVariant:
      _ObjAddProp('isVariant', true, result);
    wRawJson:
      _ObjAddProp('isJson', true, result);
    wEnum:
      begin
        _ObjAddProps(['isEnum',      true,
                      'toVariant',   'ord',
                      'fromVariant', 'Variant2' + typName], result);
        if self <> nil then
          RegisterType(fEnumerates);
      end;
    wSet:
      begin
        _ObjAddProps(['isSet',      true,
                      'toVariant',
                        SIZETODELPHI[rtti.Cache.EnumInfo.SizeInStorageAsSet],
                      'fromVariant', typName], result);
        if self <> nil then
          RegisterType(fSets);
      end;
    wGuid:
      _ObjAddProps(['toVariant',   'GuidToVariant',
                    'fromVariant', 'VariantToGuid'], result);
    wCustomAnswer:
      _ObjAddProps(['toVariant',   'HttpBodyToVariant',
                    'fromVariant', 'VariantToHttpBody'], result);
    wRecord:
      begin
        _ObjAddProp('isRecord', true, result);
        if rtti <> nil then
        begin
          _ObjAddProps(['toVariant',   typName + '2Variant',
                        'fromVariant', 'Variant2' + typName], result);
          if self <> nil then
            RegisterType(fRecords);
        end;
      end;
    wOrm:
      if (fServer <> nil) and
         (fServer.Model.GetTableIndexInheritsFrom(
           TOrmClass(rtti.ValueClass)) < 0) then
        EWrapperContext.RaiseUtf8(
          '%.ContextFromRtti: % should be part of the model', [self, typName])
      else
        _ObjAddProps(['isSQLRecord',  true,
                      'isOrm', true], result);
    wObject:
      begin
        _ObjAddProp('isObject', true, result);
        if rtti <> nil then
          _ObjAddProps(['toVariant',   'ObjectToVariant',
                        'fromVariant', typName + '.CreateFromVariant'], result);
      end;
    wArray:
      begin
        _ObjAddProp('isArray', true, result);
        if rtti <> nil then
        begin
          _ObjAddProps(['toVariant',   typName + '2Variant',
                        'fromVariant', 'Variant2' + typName], result);
          if self <> nil then
            RegisterType(fArrays);
        end;
      end;
    wBlob:
      _ObjAddProps(['isBlob',      true,
                    'toVariant',   'BlobToVariant',
                    'fromVariant', 'VariantToBlob'], result);
    wInterface:
      _ObjAddProp('isInterface', true, result);
  else
    EWrapperContext.RaiseUtf8(
      'Unexpected type % (%) for [%]', [typAsName^, ord(typ), typName]);
  end;
end;

constructor TWrapperContext.CreateFromModel(aServer: TRestServer;
  const aSourcePath, aDescriptions: TFileName);
var
  t, f, s: PtrInt;
  nfoList: TOrmPropInfoList;
  nfo: TOrmPropInfo;
  nfoOrmFieldRttiTypeName: RawUtf8;
  kind: TCrossPlatformOrmFieldKind;
  hasRecord: boolean;
  fields, services: TDocVariantData;
  field, rec: variant;
  srv: TServiceFactoryServer;
  uri: RawUtf8;
begin
  Create(aSourcePath, aDescriptions);
  fServer := aServer;
  TDocVariant.NewFast([
    @fields,
    @services]);
  // compute ORM information
  for t := 0 to fServer.Model.TablesMax do
  begin
    nfoList := fServer.Model.TableProps[t].Props.Fields;
    fields.Clear;
    fields.Init;
    hasRecord := false;
    for f := 0 to nfoList.Count - 1 do
    begin
      nfo := nfoList.List[f];
      nfoOrmFieldRttiTypeName := nfo.SqlFieldRttiTypeName;
      if nfo.InheritsFrom(TOrmPropInfoRtti) then
        field := ContextFromRtti(TYPES_ORM[nfo.OrmFieldType],
          TOrmPropInfoRtti(nfo).PropRtti, nfoOrmFieldRttiTypeName)
      else if nfo.InheritsFrom(TOrmPropInfoRecordTyped) then
      begin
        hasRecord := true;
        fHasAnyRecord := true;
        field := ContextFromRtti(wRecord,
          Rtti.RegisterType(TOrmPropInfoRecordTyped(nfo).TypeInfo),
          nfoOrmFieldRttiTypeName);
      end
      else
        EWrapperContext.RaiseUtf8('Unexpected type % for %.%',
          [nfo, fServer.Model.Tables[t], nfo.Name]);
      kind := CROSSPLATFORM_KIND[nfo.OrmFieldType];
      _ObjAddProps(['index',        f + 1,
                    'name',         nfo.Name,
                    'camelName',    LowerCamelCase(nfo.Name),
                    'snakeName',    SnakeCase(nfo.Name),
                    'sql',          ord(nfo.OrmFieldType),
                    'sqlName',      nfo.OrmFieldTypeName^,
                    'typeKind',     ord(kind),
                    'typeKindName', CROSSPLATFORMKIND_TEXT[kind],
                    'attr',         byte(nfo.Attributes)], field);
      if aIsUnique in nfo.Attributes then
        _ObjAddProp('unique', true, field);
      if nfo.FieldWidth > 0 then
        _ObjAddProp('width', nfo.FieldWidth, field);
      if f < nfoList.Count - 1 then
        _ObjAddPropU('comma', ',', field)
      else
        // may conflict with rec.comma otherwise
        _ObjAddProp('comma', null, field);
      fields.AddItem(field);
    end;
    with fServer.Model.TableProps[t] do
      rec := _JsonFastFmt('{tableName:?,className:?,classParent:?,' +
        'fields:?,isInMormotPas:%,unitName:?,comma:%}',
        [NULL_OR_TRUE[(Props.Table = TAuthGroup) or
         (Props.Table = TAuthUser)],
         NULL_OR_COMMA[t < fServer.Model.TablesMax]],
         [Props.SqlTableName, ClassNameShort(Props.Table)^,
          ClassNameShort(Props.Table.ClassParent)^,
          Variant(fields),
          Props.TableRtti.Info.RttiClass^.UnitName]);
    if hasRecord then
      rec.hasRecords := true;
    fORM.AddItem(rec);
  end;
  // compute SOA information
  if fServer.Services.Count > 0 then
  begin
    for s := 0 to fServer.Services.Count - 1 do
    begin
      srv := fServer.Services.Index(s) as TServiceFactoryServer;
      if fServer.Services.ExpectMangledUri then
        uri := srv.InterfaceMangledUri
      else
        uri := srv.InterfaceUri;
      with srv do
        rec := _ObjFast([
          'uri', uri,
          'interfaceUri',         InterfaceUri,
          'interfaceMangledUri',  InterfaceMangledUri,
          'interfaceName',        InterfaceFactory.InterfaceRtti.Name,
          'camelName',            LowerCamelCase(InterfaceFactory.InterfaceUri),
          'snakeName',            SnakeCase(InterfaceFactory.InterfaceUri),
          'GUID',                 GuidToRawUtf8(InterfaceFactory.InterfaceGuid^),
          'contractExpected',     UnQuoteSqlString(ContractExpected),
          'instanceCreation',     ord(InstanceCreation),
          'instanceCreationName', GetEnumNameTrimed(
            TypeInfo(TServiceInstanceImplementation), ord(InstanceCreation)),
          'methods',              ContextFromMethods(InterfaceFactory),
          'bypassAuthentication', ByPassAuthentication,
          'resultAsJsonObject',   ResultAsJsonObject,
          'resultAsJsonObjectWithoutResult',
            ResultAsJsonObjectWithoutResult and
            (InstanceCreation in SERVICE_IMPLEMENTATION_NOID),
          'resultAsXMLObject',    ResultAsXMLObject,
          'timeoutSec',           TimeoutSec,
          'serviceDescription',
            fDescriptions.GetValueOrNull(InterfaceFactory.InterfaceName)
        ]);
      if srv.InstanceCreation = sicClientDriven then
        rec.isClientDriven := true;
      services.AddItem(rec);
    end;
    fSOA := _ObjFast([
      'enabled',          true,
      'services',         variant(services),
      'expectMangledUri', fServer.Services.ExpectMangledUri]);
  end;
end;

constructor TWrapperContext.CreateFromUsedInterfaces(
  const aSourcePath, aDescriptions: TFileName);
var
  interfaces: TSynObjectListLightLocked;
  services: TDocVariantData;
  i: PtrInt;
begin
  Create(aSourcePath, aDescriptions);
  interfaces := TInterfaceFactory.GetUsedInterfaces;
  if interfaces = nil then
    exit;
  {%H-}services.InitFast;
  interfaces.Safe.ReadLock;
  try
    for i := 0 to interfaces.Count - 1 do
      services.AddItem(_ObjFast([
        'interfaceName',
          TInterfaceFactory(interfaces.List[i]).InterfaceRtti.Name,
        'methods', ContextFromMethods(interfaces.List[i])]));
  finally
    interfaces.Safe.ReadUnLock;
  end;
  fSOA := _ObjFast([
    'enabled',  true,
    'services', variant(services)]);
end;

function TWrapperContext.ContextArgsFromMethod(
  const meth: TInterfaceMethod): variant;
const
  DIRTODELPHI: array[TInterfaceMethodValueDirection] of string[7] = (
    'const', 'var', 'out', 'result');
  DIRTOSMS: array[TInterfaceMethodValueDirection] of string[7] = (
    // no OUT in DWS/SMS -> VAR instead
    'const', 'var', 'var', 'result');
var
  a, r: PtrInt;
  arg: variant;
  n: RawUtf8;
begin
  TDocVariant.NewFast(result);
  r := 0;
  for a := 1 to high(meth.Args) do
  begin
    with meth.Args[a] do
    begin
      arg := ContextFromRtti(TYPES_SOA[ValueType], ArgRtti);
      ShortStringToAnsi7String(ParamName^, n);
      _ObjAddProps([
        'argName',   n,
        'camelName', LowerCamelCase(n),
        'snakeName', SnakeCase(n),
        'argType',   ArgTypeName^,
        'dir',       ord(ValueDirection),
        'dirName',   DIRTODELPHI[ValueDirection],
        'dirNoOut',  DIRTOSMS[ValueDirection]], arg);
      if ValueDirection in [imdConst, imdVar] then
        _ObjAddProp('dirInput', true, arg);
      if ValueDirection <> imdConst then
        _ObjAddProp('dirOutput', true, arg);
      if ValueDirection = imdResult then
        _ObjAddProp('dirResult', true, arg);
    end;
    if a < meth.ArgsNotResultLast then
      _ObjAddPropU('commaArg', '; ', arg);
    if a = high(meth.Args) then
      _ObjAddProp('isArgLast', true, arg);
    if (meth.args[a].ValueDirection in [imdConst, imdVar]) and
       (a < meth.ArgsInLast) then
      _ObjAddPropU('commaInSingle', ',', arg);
    if (meth.args[a].ValueDirection in [imdVar, imdOut]) and
       (a < meth.ArgsOutNotResultLast)
      then
      _ObjAddPropU('commaOut', '; ', arg);
    if meth.args[a].ValueDirection <> imdConst then
    begin
      _ObjAddProps(['indexOutResult', UInt32ToUtf8(r) + ']'], arg);
      inc(r);
      if a < meth.ArgsOutLast then
        _ObjAddPropU('commaOutResult', '; ', arg);
    end;
    TDocVariantData(result).AddItem(arg);
  end;
end;

function TWrapperContext.ContextFromMethod(
  const meth: TInterfaceMethod): variant;
const
  VERB_DELPHI: array[boolean] of string[9] = (
    'procedure', 'function');
var
  d: variant;
begin
  with meth do
  begin
    result := _ObjFast([
      'methodName',      uri,
      'camelName',       LowerCamelCase(uri),
      'snakeName',       SnakeCase(uri),
      'methodIndex',     ExecutionMethodIndex,
      'verb',            VERB_DELPHI[ArgsResultIndex >= 0],
      'args',            ContextArgsFromMethod(meth),
      'argsOutputCount', ArgsOutputValuesCount]);
    if self <> nil then
    begin
      // can be called as TWraperContext(nil).ContextFromMethod
      d := fDescriptions.GetValueOrNull(InterfaceDotMethodName);
      if VarIsEmptyOrNull(d) then
        RawUtf8ToVariant(InterfaceDotMethodName, d);
      _ObjAddProp('methodDescription', d, result);
    end;
    if ArgsInFirst >= 0 then
      _ObjAddProp('hasInParams', true, result);
    if ArgsOutFirst >= 0 then
    begin
      _ObjAddProp('hasOutParams', true, result);
      if ArgsOutNotResultLast > 0 then
        _ObjAddProp('hasOutNotResultParams', true, result);
    end;
    if imfResultIsServiceCustomAnswer in Flags then
      _ObjAddProp('resultIsServiceCustomAnswer', true, result);
    if imfIsInherited in Flags then
      _ObjAddProp('isInherited', true, result);
  end;
end;

procedure TWrapperContext.AddUnit(
  const aUnitName: ShortString; addAsProperty: PVariant);
var
  unitName: variant;
  i: PtrInt;
begin
  if (aUnitName = '') or
     IdemPropName(aUnitName, 'mORMot') then
    exit;
  RawUtf8ToVariant(@aUnitName[1], ord(aUnitName[0]), unitName);
  if addAsProperty <> nil then
    _ObjAddProp('unitName', unitName, addAsProperty^);
  if (self = nil) or
     (fUnits.SearchItemByValue(unitName) >= 0) then
    // already registered
    exit;
  fUnits.AddItem(unitName);
  if fSourcePath = nil then
    exit;
  for i := 0 to high(fSourcePath) do
    FillDescriptionFromSource(fDescriptions,
      FormatString('%%.pas', [fSourcePath[i], aUnitName]));
end;

function TWrapperContext.ContextFromMethods(int: TInterfaceFactory): variant;
var
  m: PtrInt;
  methods: TDocVariantData; // circumvent FPC -O2 memory leak
begin
  AddUnit(int.InterfaceRtti.Info^.InterfaceUnitName^, nil);
  {%H-}methods.InitFast;
  for m := 0 to int.MethodsCount - 1 do
    methods.AddItem(ContextFromMethod(int.Methods[m]));
  result := variant(methods);
end;

function TWrapperContext.ContextOneProperty(const prop: TRttiCustomProp;
  const parentName: RawUtf8): variant;
var
  l, level: PtrInt;
  fullName: RawUtf8;
  isSimple: variant;
begin
  level := 0;
  if parentName = '' then
    fullName := prop.Name
  else
  begin
    FormatUtf8('%.%', [parentName, prop.Name], fullName);
    for l := 1 to length(fullName) do
      if fullName[l] = '.' then
        inc(level);
  end;
  result := ContextFromRtti(wUnknown, prop.Value, '', fullName);
  _ObjAddProps([
    'propName',     prop.Name,
    'camelName',    LowerCamelCase(prop.Name),
    'snakeName',    SnakeCase(prop.Name),
    'fullPropName', fullName], result);
  if level > 0 then
    _ObjAddPropU('nestedIdentation', RawUtf8OfChar(' ', level * 2), result);
  SetVariantNull(isSimple);
  if rcfWithoutRtti in prop.Value.Flags then
    case prop.Value.Parser of
      ptRecord:
        _ObjAddProps([
          'nestedRecord', _ObjFast([
            'nestedRecord', null,
            'fields',  ContextNestedProperties(prop.Value, fullName)])], result);
      ptArray,
      ptDynArray:
        _ObjAddProps([
          'nestedRecordArray', _ObjFast([
            'nestedRecordArray', null,
            'fields', ContextNestedProperties(prop.Value, fullName)])], result);
    else
      if not TDocVariantData(result).Exists('toVariant') then
        isSimple := true;
    end
  else if not TDocVariantData(result).Exists('toVariant') then
    isSimple := true;
  _ObjAddProp('isSimple', isSimple, result);
end;

function TWrapperContext.Context: variant;

  procedure AddDescription(var list: TDocVariantData;
    const propName, descriptionName: RawUtf8);
  var
    i: PtrInt;
    propValue: RawUtf8;
  begin
    if (list.Kind <> dvArray) or
       (fDescriptions.Count = 0) then
      exit;
    for i := 0 to list.Count - 1 do
      with _Safe(list.Values[i])^ do
        if GetAsRawUtf8(propName, propValue) then
          AddValue(descriptionName, fDescriptions.GetValueOrNull(propValue));
  end;

var
  s: PtrInt;
  authClass: TClass;
begin
  // compute the Model information as JSON
  result := _ObjFast([
    'time',          NowToString,
    'year',          CurrentYear,
    'mORMotVersion', SYNOPSE_FRAMEWORK_VERSION,
    'Executable',    VarStringOrNull(StringToUtf8(Executable.Version.DetailedOrVoid)),
    'exeInfo',       Executable.Version.VersionInfo,
    'exeName',       Executable.ProgramName,
    'hasorm',        fORM.Count > 0,
    'orm',           variant(fORM),
    'soa',           fSOA]);
  if fServer <> nil then
    _ObjAddProps([
      'root', fServer.Model.Root], result);
  if fHasAnyRecord then
    _ObjAddProp('ORMWithRecords', true, result);
  if fRecords.Count > 0 then
  begin
    AddDescription(fRecords, 'name', 'recordDescription');
    _ObjAddProps(['records',     variant(fRecords),
                  'withRecords', true,
                  'withHelpers', true], result);
  end;
  if fEnumerates.Count > 0 then
  begin
    AddDescription(fEnumerates, 'name', 'enumDescription');
    _ObjAddProps(['enumerates',     variant(fEnumerates),
                  'withEnumerates', true,
                  'withHelpers',    true], result);
  end;
  if fSets.Count > 0 then
  begin
    AddDescription(fSets, 'name', 'setDescription');
    _ObjAddProps(['sets',        variant(fSets),
                  'withsets',    true,
                  'withHelpers', true], result);
  end;
  if fArrays.Count > 0 then
  begin
    _ObjAddProps(['arrays',      variant(fArrays),
                  'withArrays',  true,
                  'withHelpers', true], result);
  end;
  if fUnits.Count > 0 then
    _ObjAddProp('units', fUnits, result);
  // add the first supported authentication class type as default
  if fServer <> nil then
    for s := 0 to fServer.AuthenticationSchemesCount - 1 do
    begin
      authClass := PClass(fServer.AuthenticationSchemes[s])^;
      if (authClass = TRestServerAuthenticationDefault) or
         (authClass = TRestServerAuthenticationNone) then
      begin
        _ObjAddProp('authClass', ToText(authClass), result);
        break;
      end;
    end;
end;

function ContextFromModel(aServer: TRestServer;
  const aSourcePath, aDescriptions: TFileName): variant;
begin
  with TWrapperContext.CreateFromModel(aServer, aSourcePath, aDescriptions) do
  try
    result := Context;
  finally
    Free;
  end;
end;

function ContextFromUsedInterfaces(
  const aSourcePath, aDescriptions: TFileName): variant;
begin
  with TWrapperContext.CreateFromUsedInterfaces(aSourcePath, aDescriptions) do
  try
    result := Context;
  finally
    Free;
  end;
end;

function ContextFromMethod(const method: TInterfaceMethod): variant;
begin
  result := TWrapperContext(nil).ContextFromMethod(method);
end;

function ContextFromMethods(int: TInterfaceFactory): variant;
begin
  result := TWrapperContext(nil).ContextFromMethods(int);
end;



{ ************ Doc/CodeGen wrapper Functions on Server Side }

procedure WrapperMethod(Ctxt: TRestServerUriContext;
  const Path: array of TFileName; const SourcePath, Descriptions: TFileName);
var
  root, templateName, templateTitle, savedName,
  templateExt, unitName, template, result, host, uri, head: RawUtf8;
  context: variant;
  SR: TSearchRec;
  i, templateFound, port: PtrInt;
begin
  // URI is e.g. GET http://localhost:888/root/wrapper/Delphi/UnitName.pas
  if (Ctxt.Method <> mGET) or
     (high(Path) < 0) then
    exit;
  templateFound := -1;
  for i := 0 to high(Path) do
    if FindFirst(MakePath([Path[i], '*.mustache']), faAnyFile, SR) = 0 then
    begin
      templateFound := i;
      break;
    end;
  if templateFound < 0 then
    Ctxt.Error(
      'Please copy some .mustache files in the expected folder (e.g. %)',
      [Path[0]])
  else
  try
    context := ContextFromModel(Ctxt.Server, SourcePath, Descriptions);
    context.uri := Ctxt.UriWithoutSignature;
    if llfHttps in Ctxt.Call^.LowLevelConnectionFlags then
      _ObjAddProps(['protocol', 'https',
                    'https',    true], context)
    else
      _ObjAddPropU('protocol', 'http', context);
    host := Ctxt.InHeader['host'];
    if host <> '' then
      _ObjAddPropU('host', host, context);
    port := GetInteger(pointer(split(host, ':', host)));
    if port = 0 then
      port := 80;
    _ObjAddProp('port', port, context);
    if PropNameEquals(Ctxt.UriMethodPath, 'context') then
    begin
      Ctxt.ReturnsJson(context, 200, {304=}true, twNone, {humanreadable=}true);
      exit;
    end;
    root := Ctxt.Server.Model.Root;
    if Ctxt.UriMethodPath = '' then
    begin
      result := '<!DOCTYPE html><html><title>mORMot Wrappers</title>' +
        '<body style="font-family:verdana;"><h1>Generated Code/Doc Wrappers</h1>' +
        '<hr><h2>Available Templates:</h2><ul>';
      repeat
        Split(StringToUtf8(SR.Name), '.', templateName, templateExt);
        templateTitle := templateName;
        i := PosExChar('-', templateName);
        if i > 0 then
        begin
          SetLength(templateTitle, i - 1);
          savedName := copy(templateName, i + 1, maxInt);
        end
        else
          savedName := 'mORMotClient';
        Split(templateExt, '.', templateExt);
        uri := FormatUtf8('<a href=/%/wrapper/%/%.%',
          [root, templateName, savedName, templateExt]);
        result := FormatUtf8(
          '%<li><b>%</b><br><i>%.%</i>  -  %>download as file</a>  -  ' +
          '%.txt>see as text</a> - %.mustache>see template</a></li><br>',
          [result, templateTitle, savedName, templateExt, uri, uri, uri]);
      until FindNext(SR) <> 0;
      result := FormatUtf8('%</ul><p>You can also retrieve the corresponding ' +
        '<a href=/%/wrapper/context>template context</a>.<hr><p>Generated by a ' +
        '<a href=http://mormot.net>Synopse <i>mORMot</i> ' +
        SYNOPSE_FRAMEWORK_VERSION + '</a> server.', [result, root]);
      Ctxt.Returns(result, HTTP_SUCCESS, HTML_CONTENT_TYPE_HEADER);
      exit;
    end;
  finally
    FindClose(SR);
  end;
  Split(Ctxt.UriMethodPath, '/', templateName, unitName);
  Split(unitName, '.', unitName, templateExt);
  if PosExChar('.', templateExt) > 0 then
  begin
    // see as text
    if PropNameEquals(Split(templateExt, '.', templateExt), 'mustache') then
      // force return .mustache
      unitName := '';
    head := TEXT_CONTENT_TYPE_HEADER;
  end
  else
    // download as file
    head := HEADER_CONTENT_TYPE + 'application/' + LowerCase(templateExt);
  templateName := templateName + '.' + templateExt + '.mustache';
  template := RawUtf8FromFile(MakePath([Path[templateFound], templateName]));
  if template = '' then
  begin
    Ctxt.Error(templateName, HTTP_NOTFOUND);
    exit;
  end;
  if unitName = '' then
    result := template // asked for .mustache template
  else
  begin
    _ObjAddProps(['templateName', templateName,
                  'filename',     unitName], context);
    result := TSynMustache.Parse(template).Render(
      context, nil, TSynMustache.HelpersGetStandardList, nil, true);
  end;
  Ctxt.Returns(result, HTTP_SUCCESS, head);
end;

function WrapperFromModel(aServer: TRestServer;
  const aMustacheTemplate, aFileName: RawUtf8; aPort: integer;
  aHelpers: TSynMustacheHelpers; aContext: PVariant;
  const aDescriptions: TFileName): RawUtf8;
var
  context: variant;
begin
  // no context.uri nor context.host here
  context := ContextFromModel(aServer, '', aDescriptions);
  with _Safe(context)^ do
  begin
    if aPort <> 0 then
      i['port'] := aPort;
    U['filename'] := aFileName;
    if aContext <> nil then
    begin
      AddFrom(aContext^);
      aContext^ := context;
    end;
  end;
  if aHelpers = nil then
    aHelpers := TSynMustache.HelpersGetStandardList;
  result := TSynMustache.Parse(aMustacheTemplate).Render(
    context, nil, aHelpers, nil, true);
end;

function WrapperFakeServer(const aTables: array of TOrmClass;
  const aRoot: RawUtf8; const aSharedServices: array of TGuid;
  const aSharedServicesContract: array of RawUtf8;
  aResultAsJsonObjectWithoutResult: boolean): TRestServerFullMemory;
var
  contract: RawUtf8;
  fake: IInterface;
  i: PtrInt;
begin
  result := TRestServerFullMemory.CreateWithOwnModel(aTables, false, aRoot);
  for i := 0 to high(aSharedServices) do
  begin
    if i <= high(aSharedServicesContract) then
      contract := aSharedServicesContract[i]
    else
      contract := '';
    result.ServiceDefine(
       TInterfaceStub.Create(aSharedServices[i], fake).LastInterfacedObjectFake,
       [aSharedServices[i]], contract).
      ResultAsJsonObjectWithoutResult := aResultAsJsonObjectWithoutResult;
  end;
end;

function WrapperForPublicAPI(const aTables: array of TOrmClass;
  const aRoot, aMustacheTemplate, aFileName: RawUtf8;
  const aSharedServices: array of TGuid;
  const aSharedServicesContract: array of RawUtf8;
  aResultAsJsonObjectWithoutResult: boolean; aPort: integer;
  aHelpers: TSynMustacheHelpers; aContext: PVariant;
  const aDescriptions: TFileName): RawUtf8;
var
  server: TRestServer;
begin
  server := WrapperFakeServer(aTables, aRoot, aSharedServices,
    aSharedServicesContract, aResultAsJsonObjectWithoutResult);
  try
    result := WrapperFromModel(server, aMustacheTemplate, aFileName, aPort,
      aHelpers, aContext, aDescriptions);
  finally
    server.Free;
  end;
end;


{ TWrapperMethodHook }

type
  TWrapperMethodHook = class(TPersistent)
  public
    SearchPath: TFileNameDynArray;
    SourcePath: TFileName;
  published
    procedure Wrapper(Ctxt: TRestServerUriContext);
  end;

procedure TWrapperMethodHook.Wrapper(Ctxt: TRestServerUriContext);
begin
  WrapperMethod(Ctxt, SearchPath, SourcePath);
end;

procedure ComputeSearchPath(const Path: array of TFileName;
  out SearchPath: TFileNameDynArray);
var
  i: PtrInt;
begin
  if length(Path) = 0 then
  begin
    // use .exe path
    SetLength(SearchPath, 1);
    SearchPath[0] := Executable.ProgramFilePath;
  end
  else
  begin
    SetLength(SearchPath, length(Path));
    for i := 0 to high(Path) do
      // also convert \ if needed on FPC
      SearchPath[i] := ExpandFileName(Path[i]);
  end;
end;

procedure AddToServerWrapperMethod(Server: TRestServer;
  const Path: array of TFileName; const SourcePath: TFileName);
var
  hook: TWrapperMethodHook;
begin
  if Server = nil then
    exit;
  hook := TWrapperMethodHook.Create;
  Server.PrivateGarbageCollector.Add(hook); // Server.Free will call hook.Free
  ComputeSearchPath(Path, hook.SearchPath);
  hook.SourcePath := SourcePath;
  Server.ServiceMethodRegisterPublishedMethods('', hook);
  Server.ServiceMethodByPassAuthentication('wrapper');
end;

function FindTemplate(const TemplateName: TFileName;
  const Path: array of TFileName): TFileName;
var
  SearchPath: TFileNameDynArray;
  i: PtrInt;
begin
  ComputeSearchPath(Path, SearchPath);
  for i := 0 to High(SearchPath) do
  begin
    result := MakePath([SearchPath[i], TemplateName]);
    if FileExists(result) then
      exit;
  end;
  result := '';
end;



{ ************ Documentation Extraction from Source Code Comments }

function ResourceDescriptionFromSource(const ResourceDestFileName: TFileName;
  const SourceFileNames: array of TFileName;
  const JsonDestFileName: TFileName): variant;
var
  desc: TDocVariantData absolute result;
  i: PtrInt;
  json: RawUtf8;
begin
  VarClear(result);
  desc.InitFast;
  for i := 0 to high(SourceFileNames) do
    FillDescriptionFromSource(desc, SourceFileNames[i]);
  json := desc.ToJson;
  if JsonDestFileName <> '' then
    JsonReformatToFile(json, JsonDestFileName);
  FileFromString(AlgoSynLZ.Compress(json), ResourceDestFileName);
end;

procedure FillDescriptionFromSource(var Descriptions: TDocVariantData;
  const SourceFileName: TFileName);
var
  desc, typeName, interfaceName: RawUtf8;
  P: PUtf8Char;
  withinCode: boolean;

  procedure IgnoreIfDef;
  begin
    // ignore any $ifdef ... $endif lines (should be at the line begining)
    repeat
      P := GotoNextLine(P);
      if P = nil then
        exit;
    until IdemPChar(GotoNextNotSpace(P), '{$ENDIF');
    P := GotoNextLine(P);
  end;

begin
  P := pointer(StringFromFile(SourceFileName));
  if P = nil then
    exit;
  withinCode := false;
  repeat
    // rough parsing of the .pas unit file to extract /// description
    P := GotoNextNotSpace(P);
    if IdemPChar(P, 'IMPLEMENTATION') then
      break; // only the "interface" section is parsed
    if IdemPChar(P, '{$IFDEF ') then
    begin
      IgnoreIfDef;
      P := GotoNextNotSpace(P);
    end;
    if (P[0] = '/') and
       (P[1] = '/') and
       (P[2] = '/') then
    begin
      desc := GetNextLine(GotoNextNotSpace(P + 3), P);
      if desc = '' then
        break;
      desc[1] := UpCase(desc[1]);
      repeat
        if P = nil then
          exit;
        P := GotoNextNotSpace(P);
        if IdemPChar(P, '{$IFDEF ') then
          IgnoreIfDef
        else if (P[0] = '/') and
                (P[1] = '/') then
        begin
          if P[2] = '/' then
            inc(P, 3)
          else
            inc(P, 2);
          P := GotoNextNotSpace(P);
          if P^ in ['$', '!'] then
          begin
            if not withinCode then
            begin
              withinCode := true;
              desc := desc + #13#10#13#10'----'; // AsciiDoc source code block
            end;
            desc := desc + #13#10;
            inc(P);
          end
          else if P^ = '-' then
          begin
            desc := desc + #13#10#13#10'-' + DESCRIPTION_ITEM_PREFIX;
            inc(P);
          end
          else
            desc := desc + ' ';
          desc := desc + GetNextLine(P, P);
        end
        else
          break;
      until false;
      if withinCode then
      begin
        // code block should end the description
        desc := desc + #13#10'----';
        withinCode := false;
      end;
      GetNextItem(P, ' ', typeName);
      if P = nil then
        exit;
      if typeName <> '' then
        if P^ = '=' then
        begin
          // simple type (record, array, enumeration, set)
          if Descriptions.GetValueIndex(typeName) < 0 then
          begin
            Descriptions.AddValue(typeName, RawUtf8ToVariant(desc));
            if typeName[1] = 'I' then
              interfaceName := Copy(typeName, 2, 128)
            else
              interfaceName := '';
          end;
        end
        else if {%H-}interfaceName <> '' then
          if PropNameEquals(typeName, 'function') or
             PropNameEquals(typeName, 'procedure') then
            if GetNextFieldProp(P, typeName) then
              Descriptions.AddValue(interfaceName + '.' + typeName,
                RawUtf8ToVariant(desc));
    end
    else
      P := GotoNextLine(P);
  until (P = nil);
end;


{ ************ FPC Dedicated Generators }

procedure ComputeFPCServerUnit(Server: TRestServer;
  const Path: array of TFileName; DestFileName: TFileName);
var
  TemplateName: TFileName;
begin
  TemplateName := FindTemplate('FPCServer-mORMotServer.pas.mustache', Path);
  if TemplateName = '' then
    exit;
  if DestFileName = '' then
    DestFileName := 'mORMotServer.pas'
  else if DestFileName[1] = PathDelim then
    DestFileName := ExtractFilePath(TemplateName) + DestFileName;
  FileFromString(WrapperFromModel(Server, RawUtf8FromFile(TemplateName),
    StringToUtf8(ExtractFileName(DestFileName)), 0), DestFileName);
end;

procedure ComputeFPCInterfacesUnit(const Path: array of TFileName;
  DestFileName: TFileName);
const
  TEMPLATE_NAME = 'FPC-mORMotInterfaces.pas.mustache';
var
  TemplateName: TFileName;
  ctxt: variant;
begin
  TemplateName := FindTemplate(TEMPLATE_NAME, Path);
  if TemplateName = '' then
    exit;
  if DestFileName = '' then
    DestFileName := 'mORMotInterfaces.pas'
  else if DestFileName[1] = PathDelim then
    DestFileName := ExtractFilePath(TemplateName) + DestFileName;
  with TWrapperContext.CreateFromUsedInterfaces('', '') do
  try
    ctxt := context;
  finally
    Free;
  end;
  ctxt.fileName := GetFileNameWithoutExtOrPath(DestFileName);
  FileFromString(TSynMustache.Parse(RawUtf8FromFile(TemplateName)).
    Render(ctxt, nil, nil, nil, true), DestFileName);
end;


{ ************ Compute Asynchronous Code from Synchronous Interface }

{$ifdef ISDELPHI20062007}
  {$WARNINGS OFF} // circumvent Delphi 2007 false positive warning
{$endif}

function GenerateAsynchServices(const services: array of TGuid;
  const queries: array of TClass; const units: array of const;
  const additionalcontext: array of const;
  Template, FileName, ProjectName, CallType, CallFunction, Key,
  KeyType, ExceptionType: RawUtf8;
  DefaultDelay: integer; const CustomDelays: array of const): RawUtf8;
var
  server: TRestServerFullMemory;
  stub: IInvokable;
  context: variant;
  service, method: PDocVariantData;
  pas, intf, meth: RawUtf8;
  delay: Int64;
  i: PtrInt;
begin
  result := '';
  if high(services) < 0 then
    exit;
  if FileName = '' then
    FileName := 'ServicesAsynch';
  if CallType = '' then
    CallType := 'TBlockingProcessPoolCall';
  if ExceptionType = '' then
    ExceptionType := 'EServiceException';
  server := TRestServerFullMemory.CreateWithOwnModel([]);
  try
    for i := 0 to high(services) do
      server.ServiceDefine(
        TInterfaceStub.Create(services[i], stub).LastInterfacedObjectFake,
        [services[i]]);
    context := ContextFromModel(server);
    _ObjAddProps([
      'filename',     FileName,
      'projectname',  ProjectName,
      'exeName',      Executable.ProgramName,
      'User',         Executable.User,
      'calltype',     CallType,
      'callfunction', CallFunction,
      'exception',    ExceptionType,
      'defaultdelay', DefaultDelay], context);
    if high(units) >= 0 then
      _Safe(context)^.O['units']^.AddItems(units);
    if Key <> '' then
      _ObjAddProps(['asynchkey',     Key,
                    'asynchkeytype', KeyType], context);
    _ObjAddProps(additionalcontext, context);
    for i := 0 to high(services) do
      if i < length(queries) then
      begin
        intf := ToUtf8(TInterfaceFactory.Guid2TypeInfo(services[i])^.RawName);
        if _Safe(context.soa.services)^.
            GetDocVariantByProp('interfaceName', intf, false, service) then
          service^.AddValue('query', ClassNameShort(queries[i])^)
        else
          EWrapperContext.RaiseUtf8('CustomDelays: unknown %', [intf]);
      end;
    i := 0;
    while i + 2 <= high(CustomDelays) do
    begin
      if VarRecToUtf8IsString(CustomDelays[i], intf) and
         VarRecToUtf8IsString(CustomDelays[i + 1], meth) and
         VarRecToInt64(@CustomDelays[i + 2], delay) then
        if _Safe(context.soa.services)^.
            GetDocVariantByProp('interfaceName', intf, false, service) and
           service^.GetAsDocVariantSafe('methods')^.
             GetDocVariantByProp('methodName', meth, false, method) then
          method^.I['asynchdelay'] := delay
        else
          EWrapperContext.RaiseUtf8('CustomDelays: unknown %.%', [intf, meth]);
      inc(i, 3);
    end;
    pas := TSynMustache.Parse(Template).
      Render(context, nil, TSynMustache.HelpersGetStandardList);
    result := StringReplaceAll(pas, ['();', ';', '():', ':']);
//FileFromString(_Safe(context)^.ToJson('','',jsonUnquotedPropName),FileName+'.json');
  finally
    server.Free;
  end;
end;

{$ifdef ISDELPHI20062007}
  {$WARNINGS ON} // circumvent Delphi 2007 false positive warning
{$endif}


{ ************ Generate Code and Doc from Command-Line }

{ TServiceClientCommandLine }

type
  /// a class implementing ExecuteFromCommandLine()
  TServiceClientCommandLine = class(TSynPersistent)
  protected
    fExe: RawUtf8;
    fOptions: TServiceClientCommandLineOptions;
    fServices: array of TInterfaceFactory;
    fDescriptions: TDocVariantData;
    fOnCall: TOnCommandLineCall;
    procedure ToConsole(const Fmt: RawUtf8; const Args: array of const;
      Color: TConsoleColor = ccLightGray; NoLineFeed: boolean = false);
    function Find(const name: RawUtf8; out service: TInterfaceFactory): boolean;
    procedure WriteDescription(desc: RawUtf8; color: TConsoleColor;
      firstline: boolean);
    procedure ShowHelp;
    procedure ShowAllServices;
    procedure ShowService(service: TInterfaceFactory);
    procedure ShowMethod(service: TInterfaceFactory; method: PInterfaceMethod);
    procedure ExecuteMethod(service: TInterfaceFactory;
      method: PInterfaceMethod; firstparam: integer);
  public
    constructor Create(const aServices: array of TGuid;
      const aOnCall: TOnCommandLineCall;
      const aDescriptions: TFileName); reintroduce;
    procedure Execute;
  end;

procedure TServiceClientCommandLine.ToConsole(const Fmt: RawUtf8;
  const Args: array of const; Color: TConsoleColor; NoLineFeed: boolean);
var
  txt: RawUtf8;
begin
  FormatUtf8(Fmt, Args, txt);
  ConsoleWrite(txt, Color, NoLineFeed, cloNoColor in fOptions);
end;

function TServiceClientCommandLine.Find(const name: RawUtf8;
  out service: TInterfaceFactory): boolean;
var
  s: PtrInt;
begin
  for s := 0 to high(fServices) do
    if IdemPropNameU(fServices[s].InterfaceUri, name) then // good FPC inlining
    begin
      service := fServices[s];
      result := true;
      exit;
    end;
  result := false;
end;

procedure TServiceClientCommandLine.WriteDescription(desc: RawUtf8;
  color: TConsoleColor; firstline: boolean);
var
  line: RawUtf8;
  P: PUtf8Char;
  i, j, k, l: PtrInt;
begin
  if not (cloNoColor in fOptions) then
    TextColor(color);
  if firstline then
    SetLength(desc, PosExChar(#13, desc) - 1);
  if desc = '' then
    exit;
  P := pointer(desc);
  repeat
    line := GetNextLine(P, P);
    if line = '' then
      continue;
    if line = '----' then
    begin
      if not (cloNoColor in fOptions) then
        TextColor(ccBrown);
    end
    else
    begin
      line := StringReplaceAll(line, ['`', '', '<<', '', '>>', '']);
      i := 1;
      repeat
        j := PosEx('[', line, i);
        if j = 0 then
          break;
        k := PosEx('](', line, j + 1);
        if k = 0 then
          break;
        l := PosEx(')', line, k + 2);
        if l = 0 then
          break;
        delete(line, k, l - k + 1);
        delete(line, j, 1);
        i := k;
      until false;
      ConsoleWriteRaw(line);
    end;
  until P = nil;
end;

procedure TServiceClientCommandLine.ShowHelp;
begin
  ToConsole('% %'#13#10, [fExe, Executable.Version.DetailedOrVoid], ccLightGreen);
  ToConsole(EXECUTEFROMCOMMANDLINEHELP, [fExe, fExe, fExe, fExe]);
end;

procedure TServiceClientCommandLine.ShowAllServices;
var
  i: PtrInt;
begin
  for i := 0 to high(fServices) do
  begin
    ToConsole('% %', [fExe, fServices[i].InterfaceUri], ccWhite);
    WriteDescription(
      fDescriptions.U[fServices[i].interfaceName], ccLightGray, true);
  end;
end;

procedure TServiceClientCommandLine.ShowService(service: TInterfaceFactory);
var
  m: PtrInt;
begin
  ToConsole('% %', [fExe, service.InterfaceUri], ccWhite);
  WriteDescription(fDescriptions.U[service.InterfaceName], ccLightGray, false);
  for m := 0 to service.MethodsCount - 1 do
    with service.Methods[m] do
    begin
      ToConsole('% % % [parameters]',
        [fExe, service.InterfaceUri, uri], ccWhite);
      WriteDescription(
        fDescriptions.U[InterfaceDotMethodName], ccLightGray, true);
    end;
end;

procedure TServiceClientCommandLine.ShowMethod(service: TInterfaceFactory;
  method: PInterfaceMethod);

  procedure Arguments(input: boolean);
  const
    IN_OUT: array[boolean] of RawUtf8 = ('OUT', ' IN');
  var
    arg: integer;  // should be integer for ArgNextInput/ArgNextOutput below
    i: PtrInt;
    line, typ: RawUtf8;
  begin
    ToConsole('%', [IN_OUT[input]], ccDarkGray, {nolinefeed=}true);
    if (not input) and
       (imfResultIsServiceCustomAnswer in method^.Flags) then
      line := ' is undefined'
    else
    begin
      line := ' { ';
      arg := 0;
      repeat
        if input then
        begin
          if not method^.ArgNextInput(arg) then
            break;
        end
        else if not method^.ArgNextOutput(arg) then
            break;
        with method^.Args[arg] do
        begin
          typ := TYPES_LANG[lngCS, TYPES_SOA[ValueType]];
          if typ = '' then
            ShortStringToAnsi7String(ArgTypeName^, typ);
          line := FormatUtf8('%"%":%, ', [line, ParamName^, typ]);
        end;
      until false;
      i := length(line);
      line[i - 1] := ' ';
      line[i] := '}';
    end;
    ToConsole('%', [line], ccDarkGray);
  end;

begin
  ToConsole('% % % [parameters]',
    [fExe, service.InterfaceUri, method.Uri], ccWhite);
  WriteDescription(
    fDescriptions.U[method.InterfaceDotMethodName], ccLightGray, false);
  if method.ArgsInputValuesCount <> 0 then
    Arguments({input=}true);
  if method.ArgsOutputValuesCount <> 0 then
    Arguments({input=}false);
end;

procedure TServiceClientCommandLine.ExecuteMethod(service: TInterfaceFactory;
  method: PInterfaceMethod; firstparam: integer);
var
  params, result: RawUtf8;
  i: PtrInt;
  cc: TConsoleColor;
  call: TRestUriParams;
begin
  // prepare the input parameters
  call.Init;
  if cloPipe in fOptions then
    call.InBody := ConsoleReadBody
  else
  begin
    for i := firstparam to ParamCount do
      params := FormatUtf8('% %', [{%H-}params, ParamStr(i)]);
    //writeln(params); // for debugging
    call.InBody := method^.ArgsCommandLineToObject(
      pointer(params), {input=}true, {raiseexcep=}true);
  end;
  // writeln(call.InBody); exit;
  if [cloVerbose, cloHeaders] * fOptions <> [] then
    ToConsole('POST %', [method.InterfaceDotMethodName], ccLightGray);
  if cloVerbose in fOptions then
    ToConsole('%', [call.InBody], ccLightBlue);
  // execute the OnCall event handler to actually run the process
  if not Assigned(fOnCall) then
    EServiceException.RaiseUtf8(
      'No Client available to call %', [method.InterfaceDotMethodName]);
  fOnCall(fOptions, service, method, call); // will set URI + Bearer
  // send output to Console
  if [cloVerbose, cloHeaders] * fOptions <> [] then
    ToConsole('HTTP %'#13#10'%', [call.OutStatus, call.OutHead], ccLightGray);
  if (call.OutBody <> '') and
     (call.OutBody[1] = '[') then
    call.OutBody := method^.ArgsArrayToObject(pointer(call.OutBody), false);
  if cloNoBody in fOptions then
    FormatUtf8('% bytes received', [length(call.OutBody)], result)
  else if (cloNoExpand in fOptions) or
          not call.OutBodyTypeIsJson then
    result := call.OutBody
  else
    JsonBufferReformat(pointer(call.OutBody), result);
  cc := ccWhite;
  if not StatusCodeIsSuccess(call.OutStatus) then
    cc := ccLightRed;
  ToConsole('%', [result], cc, {nofeed=}true);
end;

constructor TServiceClientCommandLine.Create(const aServices: array of TGuid;
  const aOnCall: TOnCommandLineCall; const aDescriptions: TFileName);
var
  desc: RawByteString;
  n, s, i: PtrInt;
begin
  inherited Create; // may have been overriden
  fExe := {$ifdef OSPOSIX} './' + {$endif} Executable.ProgramName;
  n := length(aServices);
  SetLength(fServices, n);
  s := 0;
  for i := 0 to n - 1 do
  begin
    fServices[s] := TInterfaceFactory.Get(aServices[i]);
    if fServices[s] <> nil then
      inc(s);
  end;
  if s = 0 then
    raise EServiceException.Create(
      'ExecuteFromCommandLine: no service - did you call RegisterInterfaces()?');
  if s <> n then
    SetLength(fServices, s);
  fOnCall := aOnCall;
  TDocVariant.NewFast([@fDescriptions]);
  if aDescriptions <> '' then
    desc := StringFromFile(aDescriptions);
  if {%H-}desc = '' then
    ResourceSynLZToRawByteString(WRAPPER_RESOURCENAME, desc);
  if desc <> '' then
    fDescriptions.InitJsonInPlace(pointer(desc), JSON_FAST);
end;

procedure TServiceClientCommandLine.Execute;
var
  p: array[0..3] of RawUtf8;
  a: PUtf8Char;
  i, j, n, first: PtrInt;
  s: TInterfaceFactory;
  m: PInterfaceMethod;
begin
  first := 3;
  n := 0;
  for i := 1 to ParamCount do
  begin
    StringToUtf8(ParamStr(i), {%H-}p[n]);
    a := pointer(p[n]);
    if a^ in ['-', '/'] then
    begin
      inc(a);
      if a^ = '-' then
        inc(a);
      j := PRttiInfo(TypeInfo(TServiceClientCommandLineOptions))^.
             SetEnumType^.GetEnumNameTrimedValue(a);
      if j >= 0 then
      begin
        SetBitPtr(@fOptions, j);
        if n < high(p) then
          inc(first);
        continue;
      end;
      EServiceException.RaiseUtf8(
        '%.Execute: unknown option [%]', [self, p[n]]);
    end;
    if n < high(p) then
      inc(n);
  end;
  case n of
    0:
      ShowHelp;
    1:
      if Find(p[0], s) then
        ShowService(s)
      else
        ShowAllServices;
  else
    if Find(p[0], s) then
    begin
      m := s.FindMethod(p[1]);
      if m = nil then
        ShowService(s)
      else if PropNameEquals(p[2], 'help') or
              ((m^.ArgsInputValuesCount <> 0) and
               (PosExChar('=', p[2]) = 0)) then
        ShowMethod(s, m)
      else
        ExecuteMethod(s, m, first);
    end
    else
      ShowAllServices;
  end;
  ToConsole('', [], ccDarkGray);
end;


procedure ExecuteFromCommandLine(const aServices: array of TGuid;
  const aOnCall: TOnCommandLineCall; const aDescriptions: TFileName);
begin
  with TServiceClientCommandLine.Create(aServices, aOnCall, aDescriptions) do
  try
    try
      Execute;
    except
      on E: Exception do
        ConsoleShowFatalException(E, {waitforkey=}false);
    end;
  finally
    Free;
  end;
end;


end.
